<?php
namespace Admin\Controller;

use Admin\Controller\GlobalController;

class ComicController extends GlobalController
{
    //杂志列表
    public function getlist()
    {
        $pageSize = 20;
        $where = array();
        $comicModel = M('comic');
        $count = $comicModel->where($where)->count();
        $pageObj = new \Admin\Util\Page($count, $pageSize);
        $list = $comicModel->where($where)->order('comic_id desc')->limit($pageObj->firstRow . ',' . $pageObj->listRows)->select();
        $issueModel = M('comic_issue');
        foreach ($list as $key => $row) {
            $issue_num = $issueModel->where(array('comic_id' => $row['comic_id'], 'status' => 1))->count();
            $list[$key]['issue_num'] = (int) $issue_num;
        }
        $this->assign('list', $list);
        $this->assign('page', $pageObj->show());
        $this->display();
    }

    //添加或者修改
    public function save()
    {
        $comicModel = M('comic');
        if (IS_POST) {
            $comic_id = I('post.comic_id', 0, 'intval');
            $data['comic_name'] = I('post.comic_name', 0, 'trim');
            $data['description'] = I('post.description', '', 'trim');
            if ($comic_id) {
                $comicModel->where(array('comic_id' => $comic_id))->save($data);
            } else {
                $comicModel->add($data);
            }
            $this->ajaxReturn('', 'success', 'TIP_SUCCESS');
        }
        $comic_id = I('get.comic_id', 0, 'intval');
        $info = $comicModel->where(array('comic_id' => $comic_id))->find();
        $this->assign('comic_id', $comic_id);
        $this->assign('info', $info);
        $this->display();
    }

    public function publish()
    {
        if (IS_POST) {
            $comic_id = I('post.comic_id', '', 'intval');
            $comicModel = M('comic');
            $comicModel->where(array('comic_id' => $comic_id))->setField('status', array('exp', '1 - status'));
            $this->ajaxReturn('', 'success', 'TIP_SUCCESS');
        }
    }

    public function del()
    {
        $comic_id = I('post.comic_id', 0, 'intval');
        //先检查下面有没有期刊
        $issueModel = M('comic_issue');
        $rs = $issueModel->where(array('comic_id' => $comic_id, 'status' => 1))->find();
        if ($rs) {
            $this->ajaxReturn('', '漫画下有已经上线的期刊不能删除', 'TIP_ERROR');
        }
        $comicModel = M('comic');
        $comicModel->where(array('comic_id' => $comic_id))->delete();
        $this->ajaxReturn('', 'success', 'TIP_SUCCESS');
    }
}